import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

if __name__ == '__main__':
    # 初始化三维坐标系
    fig = plt.figure(figsize=(10, 8))
    ax = fig.add_subplot(111, projection='3d')

    # ------------------------------
    # 计算平面方程
    # ------------------------------
    v1 = np.array([1, 4, 2])
    v2 = np.array([0, 3, 3])

    # 计算法向量（叉乘）
    normal = np.cross(v1, v2)  # 结果: (6, -3, 3)
    a, b, c = normal / 3  # 简化为 (2, -1, 1)


    # 平面方程: 2x - y + z = 0 → z = -2x + y
    def plane(x, y):
        return -2 * x + y


    # ------------------------------
    # 生成平面数据
    # ------------------------------
    x_range = np.linspace(-5, 5, 20)
    y_range = np.linspace(-5, 5, 20)
    X, Y = np.meshgrid(x_range, y_range)
    Z = plane(X, Y)

    # 绘制平面
    ax.plot_surface(X, Y, Z, alpha=0.5, color='cyan', label='Plane')

    # ------------------------------
    # 绘制向量 v1 和 v2
    # ------------------------------
    # 向量从原点 (0,0,0) 出发
    origin = np.array([0, 0, 0])

    ax.quiver(*origin, *v1, color='red', label='$\mathbf{v}_1=(1,4,2)$', linewidth=2, arrow_length_ratio=0.1)
    ax.quiver(*origin, *v2, color='blue', label='$\mathbf{v}_2=(0,3,3)$', linewidth=2, arrow_length_ratio=0.1)

    # ------------------------------
    # 优化坐标轴显示
    # ------------------------------
    # 隐藏背景网格平面
    ax.xaxis.pane.fill = False
    ax.yaxis.pane.fill = False
    ax.zaxis.pane.fill = False

    # 移动 X/Y 轴到原点
    ax.spines['bottom'].set_position(('data', 0))
    ax.spines['left'].set_position(('data', 0))
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)

    # 设置坐标轴范围和标签
    ax.set(xlim=(-5, 5), ylim=(-5, 5), zlim=(-5, 5))
    ax.set_xlabel('X', fontsize=12, color='red', labelpad=15)
    ax.set_ylabel('Y', fontsize=12, color='green', labelpad=15)
    ax.set_zlabel('Z', fontsize=12, color='blue', labelpad=15)

    # 调整视角
    ax.view_init(elev=20, azim=45)

    # 显示图例和标题
    # ax.legend(loc='upper right', fontsize=10)
    ax.set_title('Plane Defined by Vectors $\mathbf{v}_1=(1,4,2)$ and $\mathbf{v}_2=(0,3,3)$', pad=20)

    plt.show()
